/*================================================================
*   Copyright (C) 2024 baichao All rights reserved.
*
*   文件名称：client.c
*   创 建 者：baichao
*   创建日期：2024年09月24日
*   描    述：
*
================================================================*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080
#define BUFFER_SIZE 1024

int main() {
    int client_socket;
    struct sockaddr_in server_addr;
    char buffer[BUFFER_SIZE];
    char message[BUFFER_SIZE];

    // 创建TCP套接字
    client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket == -1) {
        perror("无法创建套接字");
        exit(EXIT_FAILURE);
    }

    // 服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");  // 服务器IP

    // 连接服务器
    if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("连接失败");
        close(client_socket);
        exit(EXIT_FAILURE);
    }
    printf("连接到服务器...\n");

    // 循环发送请求
    while (1) {
        printf("请输入命令 (INSERT <data>, QUERY, EXIT): ");
        fgets(message, BUFFER_SIZE, stdin);

        // 移除换行符
        message[strcspn(message, "\n")] = 0;

        // 处理退出命令
        if (strcmp(message, "EXIT") == 0) {
            break;
        }

        // 发送请求
        if (send(client_socket, message, strlen(message), 0) == -1) {
            perror("发送失败");
            continue;
        }
        printf("发送请求: %s\n", message);

        // 接收响应
        int recv_size = recv(client_socket, buffer, BUFFER_SIZE, 0);
        if (recv_size == -1) {
            perror("接收失败");
            break;
        } else if (recv_size == 0) {
            printf("服务器已关闭连接\n");
            break;
        }
        buffer[recv_size] = '\0';  // 确保字符串以 '\0' 结束
        printf("服务器响应: %s\n", buffer);
    }

    // 关闭套接字
    close(client_socket);
    printf("客户端已关闭\n");
    return 0;
}
